import { applyMiddleware, createStore, Store } from "redux";
import createSagaMiddleware from "redux-saga";
import { RootState } from "../interface/state";
import breezeReducer from '../reducer';
import rootService from '../saga';
import { breezeLeafStore } from "../utils/constant";
import { composeWithDevTools } from 'redux-devtools-extension';

let stores: { [key: string]: Store<RootState> } = {};

export const configureStore = (initialState: RootState, storeId?: string) => {
  storeId = storeId || breezeLeafStore;

  const sagaMiddleware = createSagaMiddleware();

  stores[storeId] = createStore(
    breezeReducer,
    { $$STORE_ID: { id: storeId }, ...initialState },
    composeWithDevTools(applyMiddleware(sagaMiddleware))
  );

  sagaMiddleware.run(rootService);

  return stores[storeId];
}

export const getStore = (storeId: string) => {
  return stores[storeId];
}